<!doctype html>
<html lang="zh-CN">
  <head>
    <!-- 必须的 meta 标签 -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap 的 CSS 文件 -->
    <link href="public/static/node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="public/static/node_modules/bootstrap-icons/font/bootstrap-icons.css">
    <link rel="stylesheet" href="public/static/node_modules/@fortawesome/fontawesome-free/css/all.css">
    <link href="public/static/node_modules/bootstrap-table/dist/bootstrap-table.min.css" rel="stylesheet">

    <script type="text/javascript" src="public/static/node_modules/jquery/dist/jquery.min.js"></script>
    <script type="text/javascript" src="public/static/node_modules/layer-src/dist/layer.js"></script>
    <script type="text/javascript">
    var myloading = layer.msg('加载中', {
      icon: 16
      ,shade: 0.01
      ,time: false
    });

    window.setInterval(function () {
      if (window.document.readyState == "complete") { 
        layer.close(myloading);
      } 
    }, 700);
    </script>

    <title>角色管理</title>
  </head>
  <body class="pt-5">
    <div id="nav-div"></div>
    <div class="container-fluid pt-3">
      <div class="row">
        <div class="col">
          <table id="table"></table>
        </div>
      </div>
    </div>

    <!-- addModal -->
    <div class="modal fade" id="addModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false" aria-labelledby="addModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="addModalLabel">新增角色</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body" id="addForm">
            <form class="mb-5 ms-1 me-1">
              <input type="hidden" id="id" name="id" value="">
              <div class="mb-3">
                <label for="role_name" class="form-label">角色名</label>
                <input type="text" class="form-control" id="role_name" name="role_name" required>
              </div>
              <div class="mb-3">
                <label for="groups" class="form-label">分组名</label>
                <input type="text" class="form-control" id="groups" name="groups">
              </div>
              <div class="mb-3">
                <label for="status" class="form-label">状态</label>
                <div class="form-check form-switch">
                  <input class="form-check-input" type="checkbox" id="status" name="status" value="1" required checked>
                  <label class="form-check-label" for="status">启用|禁用</label>
                </div>
              </div>
              <div class="mb-3">
                <label for="home_page" class="form-label">主页</label>
                <input type="text" class="form-control" id="home_page" name="home_page" value="?">
              </div>
              <button type="button" class="btn btn-primary" id="addBtn">新增</button>
              <button type="button" class="btn btn-primary" id="editBtn">保存</button>
            </form>
          </div>
        </div>
      </div>
    </div>

    <!-- setAuthModal -->
    <div class="modal fade" id="setAuthModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false" aria-labelledby="setAuthModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-xl modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="setAuthModalLabel">授权</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body" id="addForm">
            <form class="mb-5 ms-1 me-1">
              <input type="hidden" id="authorize-id" value="" required>
              <div class="mb-3">
                <label for="authorize-role_name" class="form-label">角色名</label>
                <input type="text" class="form-control" id="authorize-role_name" name="authorize-role_name" required readonly>
              </div>
              <input type="hidden" id="authorize-nodes" value="">
              <div class="mb-3">
                <label for="new_password" class="form-label">授权信息</label>
                <div class="accordion" id="accordionPanelsStayOpenExample"></div>
              </div>
              <button type="button" class="btn btn-primary" id="saveAuthBtn">保存</button>
            </form>
          </div>
        </div>
      </div>
    </div>

    <!-- 包含 Popper 的 Bootstrap 集成包 -->
    <script src="public/static/node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="public/static/node_modules/bootstrap-table/dist/bootstrap-table.min.js"></script>
    <script src="public/static/node_modules/bootstrap-table/dist/bootstrap-table-locale-all.min.js"></script>
    <script src="public/static/node_modules/bootstrap-table/dist/extensions/auto-refresh/bootstrap-table-auto-refresh.min.js"></script>
    <script src="public/static/node_modules/bootstrap-table/dist/extensions/export/bootstrap-table-export.min.js"></script>
    <script src="public/static/node_modules/bootstrap-table/dist/extensions/mobile/bootstrap-table-mobile.min.js"></script>
    <script src="public/static/node_modules/bootstrap-table/dist/extensions/print/bootstrap-table-print.min.js"></script>
    <!-- tableExport.jquery.plugin -->
    <script type="text/javascript" src="public/static/plugin/tableExport.jquery.plugin/libs/FileSaver/FileSaver.min.js"></script>
    <script type="text/javascript" src="public/static/plugin/tableExport.jquery.plugin/libs/js-xlsx/xlsx.core.min.js"></script>
    <script type="text/javascript" src="public/static/plugin/tableExport.jquery.plugin/libs/jsPDF/jspdf.min.js"></script>
    <script type="text/javascript" src="public/static/plugin/tableExport.jquery.plugin/libs/jsPDF-AutoTable/jspdf.plugin.autotable.js"></script>
    <script type="text/javascript" src="public/static/plugin/tableExport.jquery.plugin/libs/pdfmake/pdfmake.min.js"></script>
    <script type="text/javascript" src="public/static/plugin/tableExport.jquery.plugin/libs/pdfmake/vfs_fonts.js"></script>
    <script type="text/javascript" src="public/static/plugin/tableExport.jquery.plugin/libs/es6-promise/es6-promise.auto.min.js"></script>
    <script type="text/javascript" src="public/static/plugin/tableExport.jquery.plugin/libs/html2canvas/html2canvas.min.js"></script>
    <script type="text/javascript" src="public/static/plugin/tableExport.jquery.plugin/tableExport.min.js"></script>
    <script type="text/javascript" src="public/static/common/js/index.js"></script>
    

    <script type="text/javascript">
      $(document).ready(function() {
        // 导航栏
        $('#nav-div').load("public/static/common/navbar/navbar-admin.html");

        //用户列表
        $('#table').bootstrapTable({
          columns: [
            {field: 'id', title: 'ID', sortable: true, footerFormatter: groupByTitle}, 
            {field: 'role_name', title: '角色名', sortable: true, footerFormatter: getCount}, 
            {field: 'groups', title: '分组', sortable: true}, 
            {field: 'status', title: '状态', sortable: true, formatter: statusBtn}, 
            {field: 'nodes', title: '所有节点', visible: false}, 
            {field: 'create_time', title: '创建时间', visible: false, sortable: true, formatter: getdate}, 
            {field: 'update_time', title: '更新时间', visible: false, sortable: true, formatter: getdate},
            {field: 'home_page', title: '主页', visible: false},
            {field: 'id', title: '操作', formatter: option},
          ],
          method: 'post',
          url: '?m=admin&c=Role&a=getRoles',
          search: true,
          showColumns: true,
          showFullscreen: true,
          showFooter: true,
          clickToSelect: true,
          classes: 'table table-bordered table-hover',
          // 分页
          pagination: true,
          pageNumber: 1,
          pageSize: 10,
          pageList: [10, 25, 50, 100],
          // 本地化语言拓展
          locale: 'zh-CN',
          // 自动视图切换
          showToggle: true,
          smartDisplay: true,
          mobileResponsive: true,
          // 自动刷新拓展
          showRefresh: true,
          autoRefresh: true,
          autoRefreshStatus: true,
          autoRefreshInterval: 60,
          autoRefreshSilent: true,
          // 打印
          showPrint: true,
          // 导出
          showExport: true,
          exportDataType: 'basic',
          exportTypes: ['json', 'xml', 'png', 'csv', 'txt', 'sql', 'doc', 'excel', 'xlsx', 'pdf'],
          exportOptions: {
            fileName: function () {
              return '角色列表'
            }
          },
        });

        // 表头工具栏 添加新增按钮
        $('.fixed-table-toolbar').append('<div class="search btn-group float-left"><button class="btn btn-outline-primary" onclick="openAddModal()"><i class="bi bi-plus-lg"></i> 新增</button></div>');

        // 表格操作列
        function option(value, row, index, field) {
          var html = '<button class="btn btn-outline-primary btn-sm me-1" onclick="openEditModal(' + value + ')">修改</button>'
          + '<button class="btn btn-outline-primary btn-sm me-1" onclick="openAuthModel(' + value + ')">授权</button>'
          + '<button class="btn btn-outline-danger btn-sm" onclick="confirmDel(' + value + ')">删除</button>';
          return html;
        }

        // 时间戳转换格式化时间
        function getdate(value, row, index, field) {
          if (value) {
            let date = new Date(parseInt(value)*1000);
            var YY = date.getFullYear() + '-';
            var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
            var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
            var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
            var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
            var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
            return YY + MM + DD +" "+hh + mm + ss;
          } else {
            return null;
          }
        }

        // 状态开关模板
        function statusBtn(value, row, index, field) {
          var status = parseInt(value) ? "checked" : "";
          var html = '<div class="form-check form-switch">'
          + '<input class="form-check-input" type="checkbox" value="' + value + '" mid="' + row.id + '" onclick="updateStatus(this)" ' + status + '>'
          + '</div>';
          return html;
        }

        // 汇总 标题
        function groupByTitle() {
            return '汇总';
        }

        // 汇总 计数
        function getCount(value) {
            var count = 0;
            for (var i=0; i<value.length;i++) {
              count += 1;
            }
            return count;
        }

        // 汇总 总值
        function getSum(value) {
            var sum = 0;
            for (var i=0; i<value.length;i++) {
              sum += parseFloat(value[i].login_num);
            }
            return sum;
        }

        //新增用户
        $('#addBtn').click(function(event) {
            /* Act on the event */
            var field = {
              role_name: $('#role_name').val(),
              groups: $('#groups').val(),
              status: $('#status').prop('checked') ? 1 : 0,
              home_page: $('#home_page').val(),
            };
            $.ajax({
                url: '?m=admin&c=Role&a=insert',
                type: 'post',
                dataType: 'json',
                data: field,              
                success: function(data){
                    if (data.code==200) {
                        var index = layer.alert(data.msg, {
                            title: '提示'
                        }, function () {
                            // 关闭弹出层
                            layer.close(index);
                            $('#addModal').modal('hide');
                            $('#table').bootstrapTable('refresh');
                        });
                    }else{
                        layer.msg(data.msg);
                    }
                }
            });
        });

        //更新角色
        $('#editBtn').click(function(event) {
            /* Act on the event */
            var field = {
              id: $('#id').val(),
              role_name: $('#role_name').val(),
              groups: $('#groups').val(),
              status: $('#status').prop('checked') ? 1 : 0,
              home_page: $('#home_page').val(),
            };
            $.ajax({
                url: '?m=admin&c=Role&a=update',
                type: 'post',
                dataType: 'json',
                data: field,          
                success: function(data){
                    if (data.code==200) {
                        var index = layer.alert(data.msg, {
                            title: '提示'
                        }, function () {
                            // 关闭弹出层
                            layer.close(index);
                            $('#addModal').modal('hide');
                            $('#table').bootstrapTable('refresh');
                        });
                    }else{
                        layer.msg(data.msg);
                    }
                }
            });
        });

        //更新授权
        $('#saveAuthBtn').click(function(event) {
            var field = {
              id: $('#authorize-id').val(),
              nodes: $('#authorize-nodes').val(),
            };
            $.ajax({
                url: '?m=admin&c=Role&a=updateNodes',
                type: 'post',
                dataType: 'json',
                data: field,               
                success: function(data){
                    if (data.code == 200) {
                        var index = layer.alert(data.msg, {
                            title: '提示'
                        }, function () {
                            // 关闭弹出层
                            layer.close(index);
                            $('#setAuthModal').modal('hide');
                            $('#table').bootstrapTable('refresh');
                        });
                    }else{
                        layer.msg(data.msg);
                    }  
                }
            });
        });

      }); 

      //新增表单模态框
      function openAddModal() {
        $('#id').val('');
        $('#role_name').val('');
        $('#groups').val('');
        $('#status').prop('checked', 'checked');
        $('#home_page').val('?');
        $('#addBtn').show();
        $('#editBtn').hide();
        $('#addModal').modal('show');
      }

      //编辑表单模态框
      function openEditModal(id) {
        $.ajax({
            url: '?m=admin&c=Role&a=getRoleById',
            type: 'post',
            dataType: 'json',
            data: {id: id},          
            success: function(data){
                if (data.code==200) {
                    $('#id').val(data.data.id);
                    $('#role_name').val(data.data.role_name);
                    $('#groups').val(data.data.groups);
                    var status = parseInt(data.data.status) ? 'checked' : '';
                    $('#status').prop('checked', status);
                    $('#home_page').val(data.data.home_page);
                    $('#editBtn').show();
                    $('#addBtn').hide();
                    $('#addModal').modal('show');
                }else{
                    layer.msg(data.msg);
                }
            }
        });
      }

      // 设置授权模态框
      function openAuthModel(id) {
        $.ajax({
            url: '?m=admin&c=Role&a=getRoleWithGroupsById',
            type: 'post',
            dataType: 'json',
            data: {id: id},            
            success: function(data){
                if (data.code==200) {
                    $('#authorize-id').val(data.data.id);
                    $('#authorize-role_name').val(data.data.role_name);
                    $('#authorize-nodes').val(data.data.nodes + ',');
                    var nodes = data.data.node_group;
                    // console.log(nodes);
                    var accordion = '';
                    for (var i = 0; i < nodes.length; i++) {
                      var title = '<div class="accordion-item"><h2 class="accordion-header" id="panelsStayOpen-heading' + i + '">'
                      + '<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapse' + i 
                      + '" aria-expanded="true" aria-controls="panelsStayOpen-collapse' + i + '">'
                      + nodes[i]['groups']
                      + '</button></h2>'
                      + '<div id="panelsStayOpen-collapse' + i 
                      + '" class="accordion-collapse collapse" aria-labelledby="panelsStayOpen-heading' + i + '">'
                      + '<div class="accordion-body">';
                      for (var j = 0; j < nodes[i]['nodes'].length; j++) {
                        var checked = parseInt(nodes[i]['nodes'][j].allow) ? 'checked' : '';
                        var checkbox = '<div class="form-check form-check-inline">'
                          + '<input class="form-check-input" type="checkbox" id="inlineCheckbox-'+i+'-'+j+'" value="' 
                          + nodes[i]['nodes'][j].id + '" ' + checked + ' onclick="nodeCheck(this)">'
                          + '<label class="form-check-label" for="inlineCheckbox-'+i+'-'+j+'">' 
                          + nodes[i]['nodes'][j].title + '</label></div>';
                        title += checkbox;
                      }
                      title += '</div></div>';
                      accordion += title;
                    }
                    $('#accordionPanelsStayOpenExample').empty();
                    $('#accordionPanelsStayOpenExample').append(accordion);
                    $('#setAuthModal').modal('show');
                }else{
                    layer.msg(data.msg);
                }
            }
        });
      }

      function nodeCheck(obj) {
        // layer.msg($(obj).val());
        var number = $('#authorize-nodes');
        var value = $(obj).val();
        var array = number.val().split(",");
        if ($(obj).prop('checked')) {
            number.val(number.val() + value + ",");
        } else {
            var newNumber = "";
            for (var i = 0; i < array.length; i++) {
                var str = array[i];
                newNumber += (str != value && str != "" && str != null) ? str + "," : "";
            }
            number.val(newNumber);
        }
      }

      //删除询问框
      function confirmDel(id) {
        //询问框
        layer.confirm('确定删除？', {
          btn: ['确定','取消'] //按钮
        }, function(){
          layer.confirm('真的要删除？', {
            time: 20000, //20s后自动关闭
            btn: ['千真万确', '再想想']
          }, function() {
            $.ajax({
                url: '?m=admin&c=Role&a=delete',
                type: 'post',
                dataType: 'json',
                data: {id: id},              
                success: function(data){
                    if (data.code==200) {
                        layer.msg(data.msg);
                        $('#table').bootstrapTable('refresh');
                    }else{
                        layer.msg(data.msg);
                    }
                }
            });
          }, function() {
            layer.msg('唔...');
          });
        }, function(){
          layer.msg('好好考虑一下~');
        });
      }

      // 状态更新
      function updateStatus(obj) {
        var data = {
          id: $(obj).attr('mid'),
          status: $(obj).prop('checked') ? 1 : 0,
        }
        $.ajax({
            url: '?m=admin&c=Role&a=updateStatus',
            type: 'post',
            dataType: 'json',
            data: data,             
            success: function(data){
                if (data.code==200) {
                  // console.log(data)
                    layer.msg(data.msg);
                }else{
                    layer.msg(data.msg);
                } 
            }
        });
      }

    </script>
  </body>
</html>